<template>
  <div class="article-container">
    <!-- 主体内容 -->
    <main class="article-main">
      <!-- 文章头部 -->
      <article class="article-content">
        <header class="article-header">
          <h1 class="article-title">{{ article.title }}</h1>
          <div class="article-meta">
            <el-tag class="type-tag" :color="getTypeColor(article.articleType)">
              {{ showDictUtil(article.articleType, dict) }}
            </el-tag>
            <div class="meta-info">
              <span class="update-time">
                <el-icon><Clock/></el-icon>
                更新于 {{ parseTimeToDay(article.updateTime) }}
              </span>
              <div class="action-buttons">
                <el-button
                    type="primary"
                    :loading="subscribing"
                    @click="handleSubscribe"
                >
                  <template #icon>
                    <Star/>
                  </template>
                  {{ article.subscribe }} 收藏
                </el-button>
                <el-button
                    type="success"
                    :loading="liking"
                    @click="handleLike"
                >
                  <template #icon>
                    <Goods/>
                  </template>
                  {{ article.like }} 点赞
                </el-button>
              </div>
            </div>
          </div>
        </header>

        <!-- 文章内容 -->
        <section class="article-body" v-html="article.articleMx.text"></section>

        <!-- 评论区域 -->
        <section class="comment-section">
          <h2 class="section-title">评论（{{ totalComments }}）</h2>

          <!-- 评论输入 -->
          <div class="comment-editor">
            <el-avatar :src="loginUser.img" v-if="isLogin"/>
            <el-input
                v-model="commentInput"
                type="textarea"
                :rows="3"
                :placeholder="commentPlaceholder"
                :disabled="!isLogin"
                resize="none"
                class="editor-input"
            />
            <div class="editor-actions">
              <el-button
                  type="primary"
                  :disabled="!canComment"
                  @click="handleComment"
              >
                发布评论
              </el-button>
            </div>
          </div>

          <!-- 评论列表 -->
          <div class="comment-list">
            <div
                v-for="comment in commentList"
                :key="comment.id"
                class="comment-item"
            >
              <div class="comment-main">
                <el-avatar :src="comment.user.img"/>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="username">{{ comment.user.nickName }}</span>
<!--                    <span class="ip-tag">IP: {{ comment.user.userIp.province }}</span>-->
                    <span class="comment-time">
                      {{ parseTime(comment.createTime, '{y}-{m}-{d} {h}:{i}') }}
                    </span>
                  </div>
                  <pre class="comment-text">{{ comment.text }}</pre>
                  <div class="comment-actions">
                    <el-button
                        link
                        :icon="Goods"
                        @click="handleLikeComment(comment.id)"
                    >
                      {{ comment.like }}
                    </el-button>
                    <el-button
                        link
                        :icon="ChatDotRound"
                        @click="openReplyDialog(comment)"
                    >
                      回复
                    </el-button>
                    <el-button
                        v-if="comment.userId === loginUser?.id"
                        link
                        :icon="Delete"
                        @click="deleteComment(comment.id)"
                    />
                  </div>
                </div>
              </div>

              <!-- 子评论 -->
              <div
                  v-for="reply in comment.replyList"
                  :key="reply.id"
                  class="subcomment-item"
              >
                <el-avatar :src="reply.user.img"/>
                <div class="comment-content">
                  <div class="comment-header">
                    <span class="username">{{ reply.user.nickName }}</span>
                    <span
                        v-if="reply.level === '3'"
                        class="reply-target"
                    >
                      回复 @{{ reply.replyUser.nickName }}
                    </span>
<!--                    <span class="ip-tag">IP: {{ reply.user.userIp.province?reply.user.userIp.province:'' }}</span>-->
                    <span class="comment-time">
                      {{ parseTime(reply.createTime, '{y}-{m}-{d} {h}:{i}') }}
                    </span>
                  </div>
                  <pre class="comment-text">{{ reply.text }}</pre>
                  <div class="comment-actions">
                    <el-button
                        link
                        :icon="Goods"
                        @click="handleLikeComment(reply.id)"
                    >
                      {{ reply.like }}
                    </el-button>
                    <el-button
                        link
                        :icon="ChatDotRound"
                        @click="openReplyDialog(reply)"
                    >
                      回复
                    </el-button>
                    <el-button
                        v-if="reply.userId === loginUser?.id"
                        link
                        :icon="Delete"
                        @click="deleteComment(reply.id)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </section>
      </article>

      <!-- 推荐文章侧边栏 -->
      <aside class="recommend-sidebar">
        <h3 class="sidebar-title">相关推荐</h3>
        <div
            v-for="article in tjArticles"
            :key="article.id"
            class="recommend-card"
            @click="navigateToArticle(article.id)"
        >
          <el-image
              :src="article.pic"
              class="card-image"
              lazy
          />
          <div class="card-content">
            <h4 class="card-title">{{ article.title }}</h4>
            <div class="card-meta">
              <el-tag class="type-tag" size="small">
                {{ showDictUtil(article.articleType, dict) }}
              </el-tag>
              <span class="create-time">
                {{ parseTimeToDay(article.createTime) }}
              </span>
            </div>
            <div class="card-author">
              <el-icon>
                <User/>
              </el-icon>
              {{ article.user.nickName }}
            </div>
          </div>
        </div>
      </aside>
    </main>

    <!-- 回复对话框 -->
    <el-dialog
        v-model="showReplyDialog"
        :title="`回复 @${replyTarget?.user.nickName}`"
        width="600px"
        :before-close="cancelReply"
    >
      <el-input
          v-model="replyContent"
          type="textarea"
          :rows="4"
          placeholder="请输入回复内容"
          resize="none"
      />
      <template #footer>
        <el-button @click="cancelReply">取消</el-button>
        <el-button
            type="primary"
            :loading="replying"
            @click="submitReply"
        >
          发送回复
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, computed, onMounted} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {
  Star, Clock, Goods,
  ChatDotRound, Delete, User
} from '@element-plus/icons-vue'
import {
  ElMessage,
  ElMessageBox,
  ElLoading
} from 'element-plus'
import {
  getArticleById,
  getArticlePages,
  likeArticle,
  subscribeArticle
} from '@/api/articleApi'
import {
  addComment,
  addLikeApi,
  deleteCommentApi,
  getComments,
  replyApi
} from '@/api/commentApi'
import {getDict} from '@/api/common'
import {parseTimeToDay, showDictUtil} from "../../tool/commonFun.js";
import {parseTime} from "../../tool/utils.js";

// 路由相关
const route = useRoute()
const router = useRouter()
const articleId = ref(route.params.id)

// 用户状态
const isLogin = ref(false)
const loginUser = ref(null)
const commentPlaceholder = computed(() =>
    isLogin.value ? '发表你的精彩评论...' : '登录后即可参与评论'
)

// 文章数据
const article = ref({
  id: '',
  title: '',
  articleType: '',
  articleMx: {text: ''},
  subscribe: 0,
  like: 0,
  createTime: '',
  updateTime: ''
})

// 评论数据
const commentList = ref([])
const totalComments = computed(() =>
    commentList.value.reduce((total, comment) =>
        total + 1 + comment.replyList.length, 0)
)

// 推荐数据
const tjArticles = ref([])

// 字典数据
const dict = ref([])

// 评论相关
const commentInput = ref('')
const canComment = computed(() =>
    isLogin.value
)

// 回复相关
const showReplyDialog = ref(false)
const replyContent = ref('')
const replyTarget = ref(null)
const replying = ref(false)

// 加载状态
const loading = ref(false)
const subscribing = ref(false)
const liking = ref(false)

onMounted(async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '正在加载文章内容...'
  })

  try {
    await checkLoginStatus()
    await Promise.all([
      fetchArticle(),
      fetchComments(),
      fetchRecommendations(),
      fetchDictionary()
    ])
  } catch (error) {
    ElMessage.error('内容加载失败')
  } finally {
    loadingInstance.close()
  }
})

// 检查登录状态
const checkLoginStatus = () => {
  const userData = localStorage.getItem('healthUser')
  if (userData) {
    isLogin.value = true
    loginUser.value = JSON.parse(userData)
  }
}

// 获取文章详情
const fetchArticle = async () => {
  const res = await getArticleById(articleId.value)
  article.value = res.data
}

// 获取评论
const fetchComments = async () => {
  const res = await getComments(articleId.value)
  commentList.value = res.data
}

// 获取推荐
const fetchRecommendations = async () => {
  const params = {
    articleType: 'random',
    isVip: 0,
    currentPage: 1,
    pageSize: 4
  }
  const res = await getArticlePages(params)
  tjArticles.value = res.data.articles
}

// 获取字典
const fetchDictionary = async () => {
  const res = await getDict({value: 'wz_lx'})
  dict.value = res.data[0].child
}

// 处理收藏
const handleSubscribe = async () => {
  if (!isLogin.value) return showLoginAlert()

  subscribing.value = true
  try {
    await subscribeArticle({
      articleId: article.value.id,
      userId: loginUser.value.id
    })
    ElMessage.success('收藏状态已更新')
    await fetchArticle()
  } finally {
    subscribing.value = false
  }
}

// 处理点赞
const handleLike = async () => {
  if (!isLogin.value) return showLoginAlert()

  liking.value = true
  try {
    await likeArticle({
      articleId: article.value.id,
      userId: loginUser.value.id,
      likeType: 1
    })
    ElMessage.success('感谢你的点赞')
    await fetchArticle()
  } finally {
    liking.value = false
  }
}
//评论点赞
const handleLikeComment = (id) => {
  let like = {articleId: article.value.id, commentId: id, userId: loginUser.value.id, likeType: 2}
  addLikeApi(like).then(res => {
    ElMessage({message: res.msg, type: "success"})
    fetchComments()
  })
}
//删除评论
const deleteComment = (id) => {
  ElMessageBox.confirm(
      '你确定要删除这条评论吗？',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        deleteCommentApi(id).then(res => {
          ElMessage({message: res.msg, type: "success"})
          fetchComments()
        })

      })
}
// 处理评论
const handleComment = async () => {
  if (!canComment.value) return

  try {
    await addComment({
      articleId: article.value.id,
      userId: loginUser.value.id,
      text: commentInput.value.trim(),
      level: 1
    })
    ElMessage.success('评论发布成功')
    commentInput.value = ''
    await fetchComments()
  } catch (error) {
    ElMessage.error('评论发布失败')
  }
}

// 处理回复
const openReplyDialog = (comment) => {
  if (!isLogin.value) return showLoginAlert()

  replyTarget.value = comment
  showReplyDialog.value = true
}

const submitReply = async () => {
  if (!replyContent.value.trim()) return

  replying.value = true
  try {
    await replyApi({
      articleId: article.value.id,
      userId: loginUser.value.id,
      text: replyContent.value,
      level: replyTarget.value.level === '2' ? '3' : '2',
      replyId: replyTarget.value.id,
      replyUserId: replyTarget.value.userId,
      replyMainId: replyTarget.value.replyMainId || replyTarget.value.id
    })
    ElMessage.success('回复成功')
    showReplyDialog.value = false
    replyContent.value = ''
    await fetchComments()
  } finally {
    replying.value = false
  }
}

const cancelReply = () => {
  showReplyDialog.value = false
  replyContent.value = ''
}

// 其他方法
const showLoginAlert = () => {
  ElMessage.warning('请先登录后再执行此操作')
}

const getTypeColor = (typeValue) => {
  const type = dict.value.find(item => item.value === typeValue)
  return type?.color || '#dceff9'
}

const navigateToArticle = (id) => {
  router.push(`/health/article/${id}`)
}

// 样式部分较长，建议查看在线示例获取完整样式
</script>

<style lang="scss" scoped>
.article-container {
  max-width: 1440px;
  margin: 0 auto;
  padding: 24px;

  .article-main {
    display: grid;
    grid-template-columns: 1fr 300px;
    gap: 32px;
  }

  .article-content {
    background: white;
    padding: 32px;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  }

  .article-header {
    margin-bottom: 32px;
    border-bottom: 1px solid #eee;
    padding-bottom: 24px;

    .article-title {
      font-size: 32px;
      margin-bottom: 16px;
      line-height: 1.3;
      color: #333;
    }

    .article-meta {
      display: flex;
      align-items: center;
      gap: 16px;

      .type-tag {
        font-size: 14px;
        padding: 6px 12px;
      }

      .meta-info {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: #666;

        .update-time {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }

  .article-body {
    line-height: 1.8;
    font-size: 16px;
    color: #444;

    :deep(img) {
      max-width: 100%;
      border-radius: 8px;
      margin: 16px 0;
    }
  }

  .comment-section {
    margin-top: 48px;

    .section-title {
      font-size: 24px;
      margin-bottom: 24px;
    }

    .comment-editor {
      display: flex;
      gap: 16px;
      margin-bottom: 32px;

      .el-avatar {
        flex-shrink: 0;
      }

      .editor-input {
        flex: 1;

        :deep(textarea) {
          font-size: 14px;
          line-height: 1.6;
        }
      }

      .editor-actions {
        margin-top: 12px;
        text-align: right;
      }
    }

    .comment-list {
      .comment-item {
        padding: 16px;
        border-radius: 8px;
        transition: background 0.2s;

        &:hover {
          background: #f8f9fa;
        }

        .comment-main {
          display: flex;
          gap: 16px;
        }

        .subcomment-item {
          display: flex;
          gap: 16px;
          margin-left: 48px;
          padding: 12px;
          background: #f8f9fa;
          border-radius: 6px;
          margin-top: 12px;
        }

        .comment-content {
          flex: 1;

          .comment-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;

            .username {
              font-weight: 500;
            }

            .ip-tag {
              font-size: 12px;
              color: #666;
            }

            .comment-time {
              font-size: 12px;
              color: #999;
            }
          }

          .comment-text {
            white-space: pre-wrap;
            word-break: break-word;
            line-height: 1.6;
            margin: 0;
          }

          .comment-actions {
            margin-top: 8px;
            display: flex;
            gap: 16px;
          }
        }
      }
    }
  }

  .recommend-sidebar {
    .sidebar-title {
      font-size: 18px;
      margin-bottom: 16px;
      color: #333;
    }

    .recommend-card {
      margin-bottom: 16px;
      border-radius: 8px;
      overflow: hidden;
      transition: transform 0.2s;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
      }

      .card-image {
        width: 100%;
        height: 180px;
        object-fit: cover;
        border-radius: 8px;
      }

      .card-content {
        padding: 12px;

        .card-title {
          font-size: 14px;
          line-height: 1.4;
          margin: 8px 0;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .card-meta {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 8px;

          .type-tag {
            font-size: 12px;
          }

          .create-time {
            font-size: 12px;
            color: #666;
          }
        }

        .card-author {
          display: flex;
          align-items: center;
          gap: 4px;
          font-size: 12px;
          color: #666;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .article-container {
    padding: 16px;

    .article-main {
      grid-template-columns: 1fr;
    }

    .recommend-sidebar {
      display: none;
    }

    .article-content {
      padding: 16px;
    }

    .article-title {
      font-size: 24px !important;
    }
  }
}
</style>